import {Footer} from '@/components';
import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import {Helmet, history, useModel} from '@umijs/max';
import {Alert, message, Tabs, Space, Image, Form} from 'antd';
import {createStyles} from 'antd-style';
import React, {useEffect, useState} from 'react';
import {flushSync} from 'react-dom';
import Settings from '../../../../config/defaultSettings';
import {doLogin, queryLoginCaptcha, sendCaptcha} from '@/api/system/login';
import {TokenNameEnum} from "@/common/requestConstant";

const useStyles = createStyles(({token}) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});
const ActionIcons = () => {
  const {styles} = useStyles();
  return (
    <>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action}/>
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action}/>
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action}/>
    </>
  );
};
const Lang = () => {
  const {styles} = useStyles();
  return;
};
const LoginMessage: React.FC<{
  content: string;
}> = ({content}) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};
const Login: React.FC = () => {
  const [formRef] = Form.useForm<UserEntity>()
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({
    status: 200
  });
  const {initialState, setInitialState} = useModel('@@initialState');
  const {styles} = useStyles();
  const [loginParam, setLoginParam] = useState<LoginParams>({
    loginType: 'password'
  })
  const [captchaInfo, setCaptchaInfo] = useState<CaptchaInfo>()
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const getLoginCaptcha = async () => {
    const res = await queryLoginCaptcha()
    if (res?.status === 200) {
      setCaptchaInfo({
        ...res.result
      })
    }
  }
  const handleSubmit = async (values: API.LoginParams) => {
    console.log("values",values)
    try {
      // 登录
      const res = await doLogin({
        ...values,
        loginType: loginParam?.loginType,
        key: captchaInfo?.key
      });

      if (res.status === 200) {
        const defaultLoginSuccessMessage = '登录成功！';
        message.success(defaultLoginSuccessMessage);

        localStorage.setItem(TokenNameEnum.tokenHeaderName, res.result?.token as string)
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        history.replace(urlParams.get('redirect') || '/');
        setUserLoginState({
          status: res.status
        });
        return;
      }
    } catch (error:any) {
      console.log('error?.response',error?.response?.data);
      // 如果失败去设置用户错误信息
      setUserLoginState({
        status: error.response?.data.status
      });
    }
  };
  const {status} = userLoginState;

  useEffect(() => {
    const initPage = async () => {
      await getLoginCaptcha()
    }

    initPage().then()

  }, [])

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {'登录'}- {Settings.title}
        </title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg"/>}
          title="Ant Design"
          subTitle={'Ant Design 是西湖区最具影响力的 Web 设计规范'}
          initialValues={{
            autoLogin: true,
          }}
          formRef={formRef}
          actions={['其他登录方式 :', <ActionIcons key="icons"/>]}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <Tabs
            activeKey={loginParam?.loginType}
            onChange={(loginType) => setLoginParam({
              ...loginParam,
              loginType
            })}
            centered
            items={[
              {
                key: 'password',
                label: '账户密码登录',
              },
              {
                key: 'email',
                label: '邮箱登录',
              },
            ]}
          />

          {/*{userLoginState.status !== 200 && loginParam?.loginType === 'password' && (*/}
          {/*  <LoginMessage content={'错误的用户名和密码(admin/ant.design)'}/>*/}
          {/*)}*/}
          {loginParam?.loginType === 'password' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined/>,
                }}
                initialValue='750321038@qq.com'
                placeholder={'用户名: admin or user'}
                rules={[
                  {
                    required: true,
                    message: '用户名是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                initialValue='750321038@qq.com'
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined/>,
                }}
                placeholder={'密码: ant.design'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                ]}
              />
              <Space.Compact>
                <ProFormText
                  name="captcha"
                  placeholder="请输入验证码"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined/>,
                  }}
                />
                <div onClick={getLoginCaptcha}>
                  <Image height={40} preview={false} src={captchaInfo?.base64}></Image>
                </div>
              </Space.Compact>
            </>
          )}

          {/*{userLoginState.status !== 200 && loginParam?.loginType === 'email' && <LoginMessage content="验证码错误"/>}*/}
          {loginParam?.loginType === 'email' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined/>,
                }}
                name="username"
                placeholder={'请输入邮箱！'}
                rules={[
                  {
                    required: true,
                    message: '邮箱账号是必填项！',
                  },
                  // {
                  //   pattern: /^1\d{10}$/,
                  //   message: '不合法的手机号！',
                  // },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined/>,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={'请输入验证码！'}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${'秒后重新获取'}`;
                  }
                  return '获取验证码';
                }}
                name="captcha"
                phoneName='username'
                rules={[
                  {
                    required: true,
                    message: '验证码是必填项！',
                  },
                ]}
                onGetCaptcha={async (username) => {
                  const result = await sendCaptcha({
                    to: username,
                  });
                  if (!result) {
                    return;
                  }
                  message.success('获取验证码成功!');
                }}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              自动登录
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
              忘记密码 ?
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer/>
    </div>
  );
};
export default Login;
